<?php
global $msg;

$perms =& $AppUI->acl();
$canEdit = $perms->checkModuleItem('quotations', 'edit');
if (!$canEdit) {
	$AppUI->setMsg( 'Access denied', UI_MSG_ERROR, true );
	$AppUI->redirect();
}

require_once('quotation_lines.class.php');
// create a new instance of the einstein class
$obj = new CQuotation_lines();
$msg = '';	// reset the message string

// detect if a delete operation has to be processed
$del = dPgetParam($_POST, 'del', $_GET['del']);

// detect if a cancel operation has to be processed
$cancel = dPgetParam($_POST, 'cancel', 0);

$item_id = dPgetParam($_POST, 'qitem_id', $_GET['qitem_id']);
if($cancel){
	$AppUI->redirect("m=quotations");
}
else if($del){
	// Binding
	$obj->qitem_id = $item_id;
	if (!$obj->canDelete( $msg )) {
		$AppUI->setMsg( $msg, UI_MSG_ERROR );
	}
	if (($msg = $obj->deleteById($item_id))){
		$AppUI->setMsg( $msg, UI_MSG_ERROR );			// message with error flag
//		echo 'false';
	}else{
		$AppUI->setMsg( "Line deleted", UI_MSG_ALERT);		// message with success flag
//		echo 'true';
	}
}
else{
	// Validate information sender
	$quote_id = intval(dPgetParam($_POST, 'quote_id', 0));
	if($quote_id < 1){
		break;
	}
	// TODO: Validate data that user post via http

	// bind the informations (variables) retrieved via post to the quotations object
	$isNotNew = @$_POST['qitem_id'];
	if(!$obj->bind($_POST)){
	 	$AppUI->setMsg( $obj->getError(), UI_MSG_ERROR );
	}
	else{
		// Determine which apply mode was selected
		if(is_null($obj->qitem_apply_mode) or (AUTO_APPLY_VAL == $obj->qitem_apply_mode)){
			// Automatic is selected
			// Clear qitem_fixed_amount
			$obj->qitem_fixed_amount = null;
		}
		else{
			// Recaculate money number
			$obj->qitem_fixed_amount = str_replace(',' , '', $obj->qitem_fixed_amount);
			// Clear figure list
			$_POST['qitem_figure_list'] = null; // Because obj not bind with qitem_figure_list, in funstion store should bind			
		}
		
		$msg = $obj->store();
		$AppUI->setMsg( $isNotNew ? 'Quotation line updated' : 'Quotation line added', UI_MSG_OK, true );
	}
	$saveAct = dPgetParam($_POST, 'qsave_action', '');
	// do save and new
	if($saveAct=='save_new'){
		$AppUI->redirect('m=quotations&a=line_crud&quote_id='.$quote_id);
	}
	else{
		// do save
		$AppUI->redirect('m=quotations&a=quote_view&tab=0&quote_id=' . $quote_id);
	}

}
$AppUI->redirect();
?>
